import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  DatePicker,
  Modal,
  Tooltip,
  Dropdown,
  Menu,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';
import Pagination from '../../components/Pagination';
import CancelDelivery from './components/CancelDelivery';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  location: { query: any };
  logisCenterIssueList: any;
  INITINFO: any;
  checkPerm: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  orderInfo: any;
  confirmVisbile: boolean;
  cancelVisible: boolean;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    logisCenterIssueList,
    common: { INITINFO, checkPerm },
    global: { screen },
    loading,
  }: any) => ({
    logisCenterIssueList,
    INITINFO,
    checkPerm,
    screen,
    loading: loading.effects['logisCenterIssueList/fetch'],
  }),
)
class TableList extends React.Component<TableListProps, TableListState> {
  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    orderInfo: {},
    confirmVisbile: false,
    cancelVisible: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { logisCenterIssueList: { data } } = this.props;
    if (data?.content?.length) return;

    this.fetchExpressList();
    this.fetchProblemStatus();
    this.fetchIssueList();
    this.fetchAuthCheckPerm('detail');
    this.fetchAuthCheckPerm('confirm');
    this.fetchAuthCheckPerm('cancel');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
    ) {
      this.setFieldsValue();
      this.fetchIssueList();
    }
  }

  columns: any = () => {
    const { checkPerm } = this.props;
    return [
      {
        title: '运单号',
        dataIndex: 'expCode',
        width: 120,
        render: (text: any, record: any) => (
          <Tooltip title={text}>
            <div
              className="wordOmit nameLink"
              onClick={() => this.handleShowDelivery(record.id, text)}
            >
              {text}
            </div>
          </Tooltip>
        ),
      },
      {
        title: '快递公司',
        dataIndex: 'expressName',
        width: 120,
        render: (text: string) => (
          <Tooltip title={text}>
            <div className="wordOmit">{text}</div>
          </Tooltip>
        ),
      },
      {
        title: '入库时间',
        dataIndex: 'inTime',
        width: 160,
      },
      {
        title: '存放位置',
        dataIndex: 'address',
        width: 140,
        render(text: string, record: any) {
          const pkgNum = record.pkgNum === '0' || !record.pkgNum ? '' : ` ${record.pkgNum}`;
          const pkgText = record.storageType !== 5 ? pkgNum : '';
          let address:any = text ? text + pkgText : '--';

          if (record.delayWarning) {
            address = <span style={{ color: 'red' }}>{address}</span>;
          }

          return (
            <Tooltip title={address}>
              <div className="wordOmit namelink">{address}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '收件人',
        dataIndex: 'consigneePhone',
        width: 120,
        render: (text: string) => text || '--',
      },
      {
        title: '订单状态',
        dataIndex: 'statusName',
        width: 100,
      },
      {
        title: '操作',
        width: 100,
        fixed: 'right',
        dataIndex: 'id',
        render: (id: any, record: any) => (
          <>
            {checkPerm.detail && (
              <span
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => this.handleShowDelivery(id, record.expCode)}
              >
                详情
              </span>
            )}
            {(checkPerm.confirm || checkPerm.cancel)
              && (!!record.problemOrderConfirmStatus || !!record.problemOrderCancelStatus) && (
                <>
                  <Divider type="vertical" />
                  <Dropdown arrow overlay={() => this.menu(record)}>
                    <span className="operLink">
                      更多 <DownOutlined />
                    </span>
                  </Dropdown>
                </>
            )}
          </>
        ),
      },
    ];
  };

  menu = (record: any) => {
    const { checkPerm } = this.props;
    return (
      <Menu>
        {checkPerm.confirm && !!record.problemOrderConfirmStatus && (
          <Menu.Item
            className="operLink"
            style={{ color: '#1890FF', cursor: 'pointer' }}
            onClick={() => this.handleChangeConfirmModal(true, record)}
          >
            投递确认
          </Menu.Item>
        )}
        {checkPerm.cancel && !!record.problemOrderCancelStatus && (
          <Menu.Item
            className="operLink"
            style={{ color: '#1890FF', cursor: 'pointer' }}
            onClick={() => this.handleChangeCancelModal(true, record)}
          >
            取消投递
          </Menu.Item>
        )}
      </Menu>
    );
  };

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;
    const { form } = this.props;

    const {
      minId, maxId, startTime, endTime, batchDate, ...others
    } = formValues;
    if (startTime) {
      others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
    } else {
      others.start_end_time = [
        moment(
          moment()
            .subtract(2, 'days')
            .format('YYYY-MM-DD 00:00:00'),
        ),
      ];
    }

    others.batchDate = batchDate ? moment(batchDate) : '';

    form.setFieldsValue(others);
  };

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList2',
    });
  };

  /** 获取订单状态 */
  fetchProblemStatus = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'logisCenterIssueList/fetchProblemStatus' });
  };

  // 查询操作权限
  fetchAuthCheckPerm = (oper: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchAuthCheckPerm',
      payload: {
        oper,
        resource: 'logis:order_delivery',
      },
    });
  };

  // 获取数量
  handleShowCount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterIssueList/fetchCount',
      payload: this.getQueryParams(),
    });
  };

  // 获取数据
  fetchIssueList = () => {
    const { current } = this.state;
    const {
      location: { query },
      logisCenterIssueList: { data },
    } = this.props;

    const { maxId, minId, ...other } = query;
    const search = qs.stringify(other);
    const contentObj = data.content.find((item: any) => item.current === current);

    if (contentObj && search === contentObj.search) {
      this.setState({});
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: 'logisCenterIssueList/fetch',
        payload: {
          params: this.getQueryParams(),
          search,
          maxId,
          minId,
        },
      });
    }
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current, pageSize } = this.state;
    const params = { ...formValues };
    params.status = formValues.status || 0;
    params.pageIndex = current;
    params.pageSize = pageSize;

    if (params.startTime === undefined) {
      params.startTime = moment()
        .subtract(2, 'days')
        .format('YYYY-MM-DD 00:00:00');
    }

    return params;
  };

  /** 查看快递 */
  handleShowDelivery = (id: number, expCode: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${expCode}`,
      url: `/logisCenter/issue/list/detail/${id}`,
    });
  };

  /** 查询 */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form, dispatch } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const { start_end_time = [] } = fieldsValue;

      fieldsValue.startTime = start_end_time[0]
        ? moment(start_end_time[0]).format('YYYY-MM-DD HH:mm:ss')
        : moment()
          .subtract(2, 'days')
          .format('YYYY-MM-DD 00:00:00');

      fieldsValue.endTime = start_end_time[1] && moment(start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');

      delete fieldsValue.start_end_time;

      if (fieldsValue.batchDate) {
        fieldsValue.batchDate = moment(fieldsValue.batchDate).format('YYYY-MM-DD');
      }

      const query = {
        page: 1,
        ...fieldsValue,
      };

      addTab(dispatch, {
        name: '问题订单',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });

      dispatch({
        type: 'logisCenterIssueList/cleanCount',
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { dispatch, form } = this.props;

    form.resetFields();

    addTab(dispatch, {
      name: '问题订单',
      url: pathname,
      isTopMenu: true,
    });

    dispatch({
      type: 'logisCenterIssueList/cleanCount',
    });
  };

  // 确认投递弹出框
  handleChangeConfirmModal = (confirmVisbile: boolean, record?: any) => {
    this.setState({
      confirmVisbile,
      orderInfo: record
        ? {
          orderId: record.id,
          orderType: record.status,
        }
        : {},
    });
  };

  // 确认投递
  handleConfirm = () => {
    const { orderInfo } = this.state;
    const { dispatch } = this.props;
    orderInfo.search = this.getQueryParams();
    dispatch({
      type: 'logisCenterIssueList/confirm',
      payload: orderInfo,
    });
    this.handleChangeConfirmModal(false);
  };

  // 取消投递弹出框
  handleChangeCancelModal = (cancelVisible: boolean, record?: any) => {
    this.setState({
      cancelVisible,
      orderInfo: record
        ? {
          orderId: record.id,
          orderType: record.status,
        }
        : {},
    });
  };

  // 分页
  onSelectChange = (type: string) => {
    const { formValues, current, pageSize } = this.state;
    const {
      logisCenterIssueList: { data },
      dispatch,
    } = this.props;

    const query = {
      ...formValues,
      page: type === 'prev' ? current - 1 : current + 1,
      psize: pageSize,
    };

    const contentObj = data.content.find((item: any) => item.current === current);
    if (type === 'prev') {
      if (contentObj?.list?.length) {
        query.minId = contentObj.list[0].id;
      } else {
        query.minId = contentObj.maxId || contentObj.minId;
      }
      delete query.maxId;
    } else if (type === 'next') {
      const list = contentObj ? contentObj.list : [];
      query.maxId = list[list.length - 1].id;
      delete query.minId;
    }

    addTab(dispatch, {
      name: '问题订单',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  // 选择显示行数
  onShowSizeChange = (pageSize: number) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page: 1,
      psize: pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '问题订单',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      logisCenterIssueList: { statusList = [] },
      form: { getFieldDecorator },
      INITINFO: { expressList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <FormItem label="起止时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD HH:mm:ss"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="订单状态" colon={false}>
              {getFieldDecorator('status')(
                <Select allowClear placeholder="请选择" style={{ width: '100%' }}>
                  {statusList.map((item: any) => (
                    <Option key={item.key} value={item.key}>
                      {item.value}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="收件人手机" colon={false}>
              {getFieldDecorator('consigneePhone')(
                <Input allowClear type="number" placeholder="请输入" style={{ width: '100%' }} />,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="　运单号" colon={false}>
              {getFieldDecorator('expCode')(<Input allowClear placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　批次日期" colon={false}>
              {getFieldDecorator('batchDate')(
                <DatePicker disabledDate={timeLimit} placeholder="请选择日期" style={{ width: '100%' }} />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {expressList.map((express: any) => (
                    <Option value={String(express.id)} key={express.id}>
                      {express.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  render() {
    const {
      current, pageSize, confirmVisbile, cancelVisible, orderInfo,
    } = this.state;

    const {
      logisCenterIssueList: { data },
      loading,
      screen,
    } = this.props;

    const contentObj = data.content.find((item: any) => item.current === current);
    let list = contentObj ? contentObj.list : [];
    list = list || [];

    const CancelProps = {
      search: this.getQueryParams(),
      cancelVisible,
      orderInfo,
      changeCancelModal: this.handleChangeCancelModal.bind(this),
    };

    const columns = this.columns();

    if (screen === 'sm' || screen === 'lg') {
      delete columns[columns.length - 1].fixed;
    } else if (screen === 'md') {
      columns[columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            style={{ marginTop: '-12px' }}
            columns={columns}
            dataSource={list}
            pagination={false}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
          {(current > 1 || list.length > 0) && (
            <Pagination
              current={current}
              pageSize={pageSize}
              total={data.count}
              length={list.length}
              showCount={this.handleShowCount}
              onChange={this.onSelectChange}
              onShowSizeChange={this.onShowSizeChange}
            />
          )}
        </Card>

        <Modal
          title="确认投递"
          visible={confirmVisbile}
          onOk={this.handleConfirm}
          onCancel={() => this.handleChangeConfirmModal(false)}
        >
          <p>确认投递当前订单？</p>
        </Modal>

        <CancelDelivery {...CancelProps} />
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
